<?php
/**
 * Created by xun at 2020/5/9
 */

namespace app\controller;

use app\module\websocket\WebSocketAction;
use app\module\wechat\Notify;
use app\storage\Db;
use app\storage\MysqlPool;
use app\storage\OnlineUser;

class IndexController extends \app\base\BaseController
{

    public function online()
    {
        $params = $this->data['params'];
        $user = Db::getInstance()->getWxUser($params['openid']);
        if ($user) {
            OnlineUser::getInstance()->set($params['openid'], [
                'fd' => $this->fd,
                'user_id' => 0,
                'username' => $user['username'],
                'avatar' => $user['avatar'],
                'mobile_number' => $user['mobile_number'],
                'openid' => $user['openid'],
                'is_online' => 1,
                'src_id' => $params['src_id'],
                'src_type' => $params['src_type']
            ]);
            $quickMessage = Db::getInstance()->getQuickMessage($params['user_type']);
            print_r('用户:' . $user['username'] . '上线' . "\n");
            $this->sendMessage($this->fd, [
                'action' => WebSocketAction::USER_INFO_UPDATE,
                'result' => [
                    'quick_message' => $quickMessage
                ]
            ]);
        }
    }

    /**
     * c端建立会话，没做并发处理
     */
    public function session()
    {
        $server_openid = $this->data['params']['server_openid'];
        // $user_openid = $this->data['params']['user_openid'];
        $server = OnlineUser::getInstance()->get($server_openid);
        if (!$server) {
            $server = $this->makeUser($server_openid);
        }
        $client = $this->currentUser();
        try {
            $result = Db::getInstance()->createSession($server, $client);
            $data = [
                'action' => WebSocketAction::USER_CREATE_SESSION,
                'result' => [
                    'client' => $client,
                    'server' => $server,
                    'session' => $result
                ]
            ];
            // 通知B端 带上来源信息
            if ($server['is_online'] == 1 && $server['fd'] != null) {
                $src = Db::getInstance()->getSrc($client['src_id'], $client['src_type']);
                if ($src) {
                    $data['result']['src'] = [
                        'src_uuid' => $src['uuid'],
                        'src_title' => $src['title'],
                    ];
                    $this->sendMessage($server['fd'], $data);
                }
            }
            $this->sendMessage($client['fd'], $data);
        } catch (\Exception $exception) {
            $data = [
                'action' => WebSocketAction::QUERY_ERROR,
                'result' => [
                    'message' => $exception->getMessage()
                ]
            ];
            $this->sendMessage($client['fd'], $data);
        }
    }

    function clientOnline()
    {
        $currentUser = $this->currentUser();
        $result = Db::getInstance()->getSessions($currentUser['openid']);
        $users = [];
        foreach ($result as $item) {
            $user = OnlineUser::getInstance()->get($item['client_openid']);
            if ($user['is_online'] == 1 && $user['openid'] != $currentUser['openid']) {
                $user['session_id'] = $item['id'];
                $users[] = $user;
            }
        }
        $this->sendMessage($currentUser['fd'], [
            'action' => WebSocketAction::USER_ONLINE,
            'result' => $users
        ]);
    }

    public function sendToFd()
    {
        $params = $this->data['params'];
        $toUser = OnlineUser::getInstance()->get($params['to_openid']);
        $currentUser = $this->currentUser();
        $is_read = 0;
        if (!$toUser) {
            $this->makeUser($params['to_openid']);
        }
        if ($params['user_type'] == 10) {
            if ($toUser['fd'] != null && $toUser['is_online'] == 1) {
                $is_read = 1;
                $this->sendMessage($toUser['fd'], [
                    'action' => WebSocketAction::USER_P2P_MESSAGE,
                    'from' => $currentUser,
                    'to' => $toUser,
                    'message' => $params['message']
                ]);
            } else {
                $this->sendMessage($currentUser['fd'], [
                    'action' => WebSocketAction::USER_LEAVE_MESSAGE,
                    'from' => $currentUser,
                    'to' => $toUser,
                    'message' => '对方不在线，将通过离线消息送达'
                ]);
            }
        }
        if ($params['user_type'] == 20) {
            if ($toUser['is_online'] == 1) {
                $is_read = 1;
                $this->sendMessage($toUser['fd'], [
                    'action' => WebSocketAction::USER_P2P_MESSAGE,
                    'from' => $currentUser,
                    'to' => $toUser,
                    'message' => $params['message']
                ]);
            } else {
                if ($params['is_client_offline_notify'] == 0) {
                    $notify = new Notify();
                    $notify->sendTemplate($currentUser, $params['to_openid']);
                }
                $this->sendMessage($currentUser['fd'], [
                    'action' => WebSocketAction::USER_LEAVE_MESSAGE,
                    'from' => $currentUser,
                    'to' => $toUser,
                    'is_notify' => 1,
                    'message' => '对方不在线，将通过离线消息送达'
                ]);
            }
        }
        Db::getInstance()->insert($toUser, $currentUser, $params, $is_read);
    }

    /**
     * todo
     */
    public function clientDemandInfo()
    {
        $params = $this->data['params'];
        $client = OnlineUser::getInstance()->get($params['openid']);
        $currentUser = $this->currentUser();
        $src = Db::getInstance()->getSrc($client['src_id'], $client['src_type']);
        if ($src) {
            $this->sendMessage($currentUser['fd'], [
                'action' => WebSocketAction::USER_DEMAND_INFO,
                'result' => [
                    'src' => [
                        'src_uuid' => $src['uuid'],
                        'src_title' => $src['title'],
                    ]
                ]
            ]);
        }
    }

    public function history()
    {
        $params = $this->data['params'];
        $currentUser = $this->currentUser();
        $list = Db::getInstance()->getHistory($params);
        $this->sendMessage($currentUser['fd'], [
            'action' => WebSocketAction::USER_P2P_HISTORY,
            'list' => $list,
        ]);
    }

    public function makeUser($openid)
    {
        $user = Db::getInstance()->getWxUser($openid);
        echo $user;
        if (!$user) {
            // todo 用户不存在
        }
        OnlineUser::getInstance()->set($openid, [
            'fd' => null,
            'user_id' => 0,
            'username' => $user['username'],
            'mobile_number' => $user['mobile_number'],
            'avatar' => $user['avatar'],
            'openid' => $user['openid'],
            'is_online' => 0,
            'src_id' => 0,
            'src_type' => 0
        ]);

        return OnlineUser::getInstance()->get($openid);
    }

}